﻿using System.Linq;
using AutoMapper;
using API.Helpers;
using API.IRepositories;
using API.IServices;
using API.Models;
using API.Profiles;
using AutoMapper.QueryableExtensions;
using Helper.Exceptions;
using LinqKit;

namespace API.Services
{
    public class DrinkOrderService : EndUserProfileService, IDrinkOrderService
    {
        private readonly IDrinkOrderRepository _drinkOrderRepository;
        private readonly bool _validateCustomService;

        public DrinkOrderService()
            : this(DependencyInjectionHelper.Resolve<IEndUserProfile>(), DependencyInjectionHelper.Resolve<IDrinkOrderRepository>())
        {
        }

        public DrinkOrderService(IEndUserProfile authenticatedUserProfile, IDrinkOrderRepository drinkRepository, bool validateCustomService = true)
            : base(authenticatedUserProfile)
        {
            _drinkOrderRepository = drinkRepository;
            _validateCustomService = validateCustomService;
        }

        public void Delete(int id)
        {
            var model = Get(id);
            if (model == null)
                throw new ValidationException("The requested Drink Order was not found and could not be deleted.");

            _drinkOrderRepository.Delete(id);
        }

        public IQueryable<Models.DrinkOrder> Get()
        {
            return _drinkOrderRepository
                .Get()
                .AsExpandable()
                .OrderBy(e => e.Created)
                .Project()
                .To<Models.DrinkOrder>();
        }

        public Models.DrinkOrder Get(int id)
        {
            return this.Get().FirstOrDefault(c => c.Id == id);
        }



        public Models.DrinkOrder Save(Models.DrinkOrder entity)
        {
            // ValidationHelper.ValidateModel(entity, _validateCustomService);

            return SaveDrinkOrder(entity);
        }

        private DrinkOrder SaveDrinkOrder(DrinkOrder entity)
        {
            return Mapper.Map<EntityModels.DrinkOrder, Models.DrinkOrder>(_drinkOrderRepository.Save(Mapper.Map<Models.DrinkOrder, EntityModels.DrinkOrder>(entity), typeof(Models.DrinkOrder)));
        }
    }
}

